package com.jz.community.commview.view.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.util.Log;

/**
 * Created by Tony.Fan on 2017/8/4.
 */

public class ProgressDialogManager {
    private static CustomProgressDialog progressDialog;

    public static CustomProgressDialog showDialog(@NonNull Context context) {
        return showDialog(context, null);
    }

    public static CustomProgressDialog showDialog(@NonNull Context context, boolean canCancel) {
        return showDialog(context, canCancel, null);
    }

    public static CustomProgressDialog showDialog(@NonNull Context context, DialogInterface
            .OnCancelListener listener) {
        return showDialog(context, true, listener);
    }

    public static CustomProgressDialog showDialog(@NonNull Context context, Boolean canCancel, DialogInterface
            .OnCancelListener listener) {
        return showProgressDialog(context, canCancel, listener);
    }

    public static CustomProgressDialog showProgressDialog(@NonNull Context context, boolean canCancelable, DialogInterface
            .OnCancelListener listener) {
        if (progressDialog == null) {
            progressDialog = new CustomProgressDialog(context);
        } else if (progressDialog.getContext() != context) {
            Log.d("dialog", "there is a leaked window here,orign context: "
                    + progressDialog.getContext() + " now: " + context);
            dismissProgressDialog();
            progressDialog = new CustomProgressDialog(context);
        }
        progressDialog.setCancelable(canCancelable);
        if (listener != null) {
            progressDialog.setOnCancelListener(listener);
        }
        progressDialog.show();
        return progressDialog;
    }

    public static void dismissProgressDialog() {
        if (progressDialog == null) {
            return;
        }
        if (progressDialog.isShowing()) {
            try {
                progressDialog.dismiss();
                progressDialog = null;
            } catch (Exception e) {
                //捕获异常
            }
        }
    }

    public static boolean isShowing() {
        return (progressDialog != null && progressDialog.isShowing());
    }

}
